﻿using Elio.Controls;
using Elio.Interfaces;
using Elio.Sessions;
using Elio.Sessions.Widgets;
using Google.Protobuf.WellKnownTypes;

namespace Elio.Widgets;
public class WidgetCheckBox : HorizontalStackLayout, ISessionWidget
{
    private CheckBox? _checkBox;
    private Label? _label;
    public BaseSession? Session { get; set; }
    public void Init(InitOptions options)
    {
        (WidthRequest, HeightRequest) = (options.Width, options.Height);
        this.SetPoint(options.X, options.Y);
        _checkBox = new CheckBox();
        _label = new Label { Text = options.Text };
        Children.Add(_checkBox);
        Children.Add(_label);
    }

    public async Task<bool> OnViewReceive(string name, long sid, long fid, params Any[] argv)
    {
        switch (name)
        {
            case "isChecked":
                await IsChecked(sid, fid);
                break;

            case "setChecked":
                SetChecked(argv);
                break;

            case "getText":
                await GetText(sid, fid);
                break;

            case "setText":
                SetText(argv);
                break;

            default:
                return false;
        }
        return true;
    }

    private async Task IsChecked(long sid, long fid) =>
        await Session!.SendAction("onIsChecked", sid, fid, _checkBox!.IsChecked.ToAny());

    private void SetChecked(params Any[] argv) =>
        _checkBox!.IsChecked = argv[0].P2Bool();

    private async Task GetText(long sid, long fid) =>
        await Session!.SendAction("onGetText", sid, fid, _label!.Text.ToAny());

    private void SetText(params Any[] argv) => _label!.Text = argv[0].P2String();
}